package fr.uniscol.dao.impl;

import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;

import fr.uniscol.dao.IEleveDao;
import fr.uniscol.model.AnneeScolaire;
import fr.uniscol.model.Eleve;
import fr.uniscol.model.Scolarite;
import fr.uniscol.model.ServiceEnseignant;

public class EleveDaoImpl implements IEleveDao {

	private SessionFactory sessionFactory;
	
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public Eleve getEleve(AnneeScolaire annee, int id) {
		// TODO Auto-generated method stub
		return null;
	}
	
	public List<Eleve> getAllEleves(AnneeScolaire base){
		Session session = sessionFactory.getCurrentSession();
		
		Query q = session.createQuery("From Eleve Where annee_id=:annee_id");
		q.setParameter("annee_id", base.getId());
		
		return q.list();
	}
	
	public void enregistrerEleve(Eleve eleve) {
		
		Session session = sessionFactory.getCurrentSession();
		
		session.saveOrUpdate(eleve);
		
		for(Scolarite sco : eleve.getScolarites()){
			session.saveOrUpdate(sco);
		}
	}

	public List<Eleve> findElevesByServiceEnseignant(AnneeScolaire base, ServiceEnseignant service) {
		Session session = sessionFactory.getCurrentSession();
		
		Query q = session.createQuery("From Eleve as e " +
									  "join e.scolarites as sco " +
									  "join sco.structures as str " +
									  "where str.id=:structure");
		q.setParameter("structure", service.getStructure().getId());
		
		return q.list();
	}
}
